/**
 * 
 */
package de.idgard.json.transport;

import com.google.gson.reflect.TypeToken;

import de.idgard.json.IDGGson;
import de.idgard.webapp.shared.dto.transport.DataRequest;
import de.idgard.webapp.shared.dto.transport.JsonResponse;

/**
 * 
 * @author <a href="mailto:vesko.georgiev@uniscon.com">Vesko Georgiev</a>
 */
public class AsyncRequestImpl<ResultType> implements PayloadParser<ResultType>, AsyncRequest<ResultType> {

	private static class JsonResponseTokeType extends TypeToken<JsonResponse<?>> {
	}

	private Class<ResultType> resultType;
	private ServiceTransport transport;
	private String url;
	private Object payload;
	private ResultType cachedResult;
	private CacheHandler cacheHandler;

	public void setCacheHandler(CacheHandler cacheHandler) {
		this.cacheHandler = cacheHandler;
	}

	public void setCachedResult(ResultType cachedResult) {
		this.cachedResult = cachedResult;
	}

	public AsyncRequestImpl(Class<ResultType> resultType, ServiceTransport transport, String url, Object payload) {
		this.resultType = resultType;
		this.transport = transport;
		this.url = url;
		this.payload = payload;
	}

	public AsyncRequestImpl(Class<ResultType> resultType, ServiceTransport transport, String url) {
		this.resultType = resultType;
		this.transport = transport;
		this.url = url;
		this.payload = this;
	}

	public final void fire() {
		fire(new Receiver<ResultType>());
	}

	public void fire(Receiver<ResultType> result) {
		if (cachedResult != null) {
			result.onSuccess(cachedResult);
			return;
		}

		if (payload instanceof DataRequest) {
			transport.post(url, (DataRequest<?>) payload, result, this, cacheHandler);
		}
		else if (payload != this) {
			transport.post(url, new DataRequest<Object>(payload), result, this, cacheHandler);
		}
		else {
			transport.post(url, null, result, this, cacheHandler);
		}
	}

	@Override
	public ResultType parse(String payload) {
		try {
			if (Void.class.isAssignableFrom(resultType)) {
				return null;
			}
			else if (JsonResponse.class.isAssignableFrom(resultType)) {
				return IDGGson.gson().fromJson(payload, resultType);
			}
			else {
				JsonResponse<ResultType> response = IDGGson.gson().fromJson(payload, new JsonResponseTokeType().getType());
				ResultType ret = IDGGson.gson().fromJson(IDGGson.gson().toJson(response.getData()), resultType);
				return ret;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
